/// <reference path="../../../typings/index.d.ts" />
import * as dao from "../dao/dbAccess";

const WXAPP = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        this.loadingUserData();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 载入用户数据
     */
    loadingUserData() {
        this.authentication();
    },

    /**
     * 鉴别是否登陆过，**并自动跳转到home页面**
     */
    authentication: function () {
        let that = this;
        wx.getSetting({
            success(res) {
                console.log(res.authSetting);
                if (res.authSetting["scope.userInfo"]) {
                    console.log("老用户");
                    WXAPP.globalData.isLogin = true;
                    that.getUserInfo();
                }
                else {
                    console.log("用户未授权");
                }
            },
            fail(err) {
                console.error("Fail to get auth setting\n", err);
            },
            complete() {
                that.getOpenid().then(() => {
                    wx.redirectTo({
                        url: '../home/home',
                    });
                });
            }
        })
    },

    getOpenid() {
        return new Promise((resolve, reject) => {
            wx.cloud.callFunction({
                name: 'getOpenID',
            }).then((res) => {
                WXAPP.globalData.openid = res.result.openid;
                console.log("OpenID: ", WXAPP.globalData.openid);
                dao.checkUserDatabase().then(() => {
                    resolve(res);
                });
            }).catch((err) => {
                console.error("In app 获取OpenID失败\n", err);
                reject(err);
            })
        });
    },

    /**
     * 获取用户信息
     */
    getUserInfo () {
        return new Promise((resolve, reject) => {
            wx.getUserInfo({
                success(res) {
                    console.log(res);
                    WXAPP.globalData.userInfo = res.userInfo;
                    console.log('欢迎回来！', res.userInfo.nickName);
                    resolve(res);
                },
                fail(err) {
                    console.error(err);
                    reject(err);
                }
            });
        })
    },

})